import { createApp, h, type VNode } from "vue";
import MessageBox from "./MessageBox.vue";
import { useI18n } from "@/plugins/i18n";
import type { Action } from "./message-box.type";

const messageBox = options => {
  return new Promise((resolve, reject) => {
    const app = createApp({
      render() {
        return h(MessageBox, {
          ...options,
          onAction: (action: Action, value: string) => {
            let resolveValue: Action | { value: string; action: Action };
            if (options.showInput) {
              resolveValue = { value, action };
            } else {
              resolveValue = action;
            }
            if (options.callback) {
              options.callback(resolveValue);
            } else {
              if (action === "cancel" || action === "close") {
                if (options.distinguishCancelAndClose && action !== "cancel") {
                  reject("close");
                } else {
                  reject("cancel");
                }
              } else {
                resolve(resolveValue);
              }
            }
            app.unmount();
          },
          onClose: () => {
            reject(false);
            app.unmount();
          }
        });
      }
    });

    app.use(useI18n);

    const container = document.createElement("div");
    document.body.appendChild(container);
    app.mount(container);
  });
};

type MessageType = string | VNode;

const message = {
  alert(
    message: MessageType,
    title = "提示",
    option = {
      type: "warning",
      showCancel: false
    }
  ) {
    return messageBox({
      message,
      title,
      option,
      showCancel: option?.showCancel ?? true,
      boxType: "alert"
    });
  },
  confirm(
    message: MessageType,
    title = "提示",
    option = {
      type: "warning",
      showCancel: true
    }
  ) {
    return messageBox({
      message,
      title,
      option,
      boxType: "confirm",
      showCancel: option?.showCancel ?? true
    });
  },
  prompt(message: MessageType, title = "提示", option = {}) {
    return messageBox({
      message,
      title,
      option,
      showInput: true,
      showCancel: true,
      boxType: "prompt"
    });
  }
};

export const MessageBoxPlugin = {
  install(app) {
    app.config.globalProperties.$auMessageBox = message;
  }
};

export default { ...message };
